// Third Party
import themeConfig from '@configs/themeConfig'
import { Icon } from '@iconify/react'
import { EditorState, convertToRaw } from 'draft-js'
import draftToHtml from 'draftjs-to-html'
import { useCallback, useEffect, useRef, useState } from 'react'
import { Editor } from 'react-draft-wysiwyg'
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'
import { Check, Paperclip, Trash2 } from 'react-feather'
import { useDispatch, useSelector } from 'react-redux'
import { Alert, Button, Input, Label, Spinner } from 'reactstrap'
import RobustWebSocket from 'robust-websocket'
import { SOCKET_MAIN_URL } from '../../constants'
// Components
import {
  receiveMessageAction
  // sendMessageAction
} from '../../redux/messages/messageAction'

import {
  addMessagesHandler,
  resetReceiveMessages
} from '../../redux/messages/messageSlice'
import Chat from './Chat'
let connectionEstablish = false

const ChatBox = () => {
  const dispatch = useDispatch()
  const messagesEndRef = useRef(null)
  const chatContainerRef = useRef(null)
  const [images, setImages] = useState([])
  const [socket, setSocket] = useState(null)
  const [value, setValue] = useState(() => EditorState.createEmpty())
  const imageHandler = (e) => setImages([...images, e.target.files[0]])
  const { getMyProfile } = useSelector((state) => state.myProfile)
  const getMyProvider = useSelector((state) => state.provider.getMyProvider)
  const { getAllMessages, loading, receiveLoading } = useSelector(
    (state) => state.messages
  )
  const rows = getAllMessages?.data
  const limit = getAllMessages?.limit
  const count = getAllMessages?.count
  // const reverseArray = rows ? [...rows].reverse() : []

  const socketHandler = (socket) => {
    setSocket(socket)
  }
  const handleScroll = () => {
    const scrollTop = chatContainerRef.current.scrollTop
    const scrollHeight = chatContainerRef.current.scrollHeight
    const clientHeight = chatContainerRef.current.clientHeight

    if (scrollTop === 0 && scrollHeight > clientHeight) {
      if (limit >= count || !!receiveLoading) return
      dispatch(receiveMessageAction({ offset: 0, limit: limit + 10 }))
    }
  }
  // useEffect(() => {
  //   dispatch(getMyProviderAction())
  //   return () => {
  //     dispatch(resetGetProvider())
  //   }
  // }, [])
  useEffect(() => {
    dispatch(receiveMessageAction({ offset: 0, limit }))
    return () => {
      dispatch(resetReceiveMessages())
    }
  }, [])

  useEffect(() => {
    chatContainerRef.current.addEventListener('scroll', handleScroll)
    return () => {
      chatContainerRef.current?.removeEventListener('scroll', handleScroll)
    }
  }, [handleScroll])

  // const scrollToBottom = () => {
  //   messagesEndRef.current.scrollIntoView({ behavior: 'smooth' })
  //   useEffect(scrollToBottom, [!rows?.length, count])
  // }
  const handleSendMessage = () => {
    const newMessage = {
      message: draftToHtml(convertToRaw(value.getCurrentContent())),
      provider: getMyProvider.id,
      from_type: 1,
      created_at: Date.now() / 1000
    }
    dispatch(addMessagesHandler(newMessage))
    setValue(() => EditorState.createEmpty())
    if (connectionEstablish) {
      socket.send(JSON.stringify(newMessage))
    } else {
      const intervalId = setInterval(() => {
        if (connectionEstablish) {
          socket.send(JSON.stringify(newMessage))
          clearInterval(intervalId)
        }
      }, 1000)
    }
    // const text = convertToRaw(value.getCurrentContent())

    // if (text.blocks[0].text !== '' || images?.length > 0) {
    //   const document = new FormData()
    //   {
    //     images.map((file) => document.append('files', file))
    //   }
    //   if (text.blocks[0].text !== '') {
    //     document.append(
    //       'content',
    //       draftToHtml(convertToRaw(value.getCurrentContent()))
    //     )
    //   }

    //   dispatch(
    //     sendMessageAction({
    //       data: document,
    //       limit,
    //       callback: () => {
    //         setImages([])
    //         setValue(() => EditorState.createEmpty())
    //       }
    //     })
    //   )
    // }
  }
  const receiveMessagesHandler = (newMessage) => {
    dispatch(addMessagesHandler(newMessage))
  }
  const buildConnection = useCallback((token, providerId, clientId) => {
    // const url = `wss://ethera.sparkai.ca/ws/pr/room_${providerId}_${clientId}?token=${token}`
    const url = `${SOCKET_MAIN_URL}/ws/pr/room_${providerId}_${clientId}?token=${token}`

    const ws = new RobustWebSocket(url)
    ws.addEventListener('open', function () {
      connectionEstablish = true
    })
    ws.addEventListener('message', function (event) {
      receiveMessagesHandler(JSON.parse(event.data))
    })

    return ws
  }, [])
  const deleteFile = (id) => {
    setImages(images.filter((item, i) => i !== id))
  }
  const handleChange = (e) => setValue(e)
  const text = convertToRaw(value.getCurrentContent())
  useEffect(() => {
    if (getMyProvider) {
      const socket = buildConnection(
        sessionStorage.getItem('accessToken'),
        getMyProvider.id,
        JSON.parse(sessionStorage.getItem('userData')).user_id
      )
      socketHandler(socket)
    }
    // return () => {
    //   connectionEstablish = false
    // }
  }, [getMyProvider])
  return (
    <>
      <div className="chat-box">
        <div className="chat-message my-1 " ref={chatContainerRef}>
          {receiveLoading ? (
            <div className="text-center">
              <Spinner size="15" />
            </div>
          ) : null}
          {rows?.length === 0 && !receiveLoading ? (
            <div
              className="bg-transparent text-center py-2"
              style={{
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center'
              }}
            >
              <img
                src={themeConfig.app.appLogoImage}
                alt="logo-dark"
                height="70px"
                className="mb-1"
              />

              <p>Start Chat with your Provider</p>
            </div>
          ) : (
            <Chat messagesList={rows} receiveLoading={receiveLoading} />
          )}
          <div ref={messagesEndRef} />
        </div>

        <div className="py-1 alert-box-main border-top border-bottom d-flex px-2">
          <Alert color="danger">
            <Icon
              icon="akar-icons:triangle-alert-fill"
              color="danger"
              width="20"
              height="20"
            />
          </Alert>

          <Alert color="danger" className="alert-box ">
            This messaging platform is not intended for immediate support,
            crisis intervention, or as a replacement or therapeutic sevices. if
            you are experiencing an emergency or crisis and need immediate help,
            call 911 or go to the nearest emergency room
          </Alert>
        </div>

        <div className="editor">
          <Editor
            toolbarClassName="toolbarClassName"
            wrapperClassName="wrapperClassName"
            editorClassName="editorClassName"
            toolbar={{
              options: ['inline', 'list', 'history'],
              list: { inDropdown: false, options: ['unordered', 'ordered'] },
              inline: { inDropdown: false, options: ['bold', 'italic'] },
              history: { inDropdown: false }
            }}
            editorState={value}
            onEditorStateChange={handleChange}
          />
        </div>

        <div className="d-flex justify-content-between align-items-start sm-screen-styling">
          <div className="px-2 mt-1">
            {images.length > 0 &&
              images.map((item, i) => (
                <div className="d-flex justify-content-between" key={i}>
                  <p className="text-ellipsis">{item?.name || '--'}</p>
                  <span className="pl-2 pointer" onClick={() => deleteFile(i)}>
                    <Trash2 size={16} stroke="red" />
                  </span>
                </div>
              ))}
          </div>
          <div className="d-flex justify-content-end align-items-center">
            <div>
              <Label htmlFor="attachLink" className="mt-1 attachLink">
                <Paperclip size={18} />
              </Label>
              <Input
                type="file"
                onChange={imageHandler}
                id="attachLink"
                style={{ display: 'none' }}
              />
            </div>
            <div>
              <Button
                onClick={() => handleSendMessage()}
                className="float-right reqbgColor px-3 mt-1 mx-2"
                size="sm"
                disabled={
                  loading ||
                  parseInt(getMyProfile?.messaging) === 2 ||
                  (text.blocks[0].text === '' && images?.length === 0)
                }
              >
                {loading ? (
                  <Spinner size="sm" className="spinner-size" />
                ) : (
                  <Check size={15} />
                )}
                <span className="px-1">Send</span>
              </Button>
            </div>
          </div>
        </div>
      </div>
    </>
  )
}

export default ChatBox
